package android.pot.com.smartcar.tool;

import android.pot.com.smartcar.application.MyApplication;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

/**
 * Created by zhaoshilu on 2017/12/22.
 */
public class LocationHelper {

    private LocationCallBack callBack;

    private static LocationHelper helper;



    private LocationClient locationClient;

    private BDLocationListener locationListener = new MyBDLocationListener();



    private LocationHelper() {

        //第一步实例化定位核心类

        locationClient = new LocationClient(MyApplication.getContext(), getLocOption());

        //第二步设置位置变化回调监听

        locationClient.registerLocationListener(locationListener);

    }



    public static LocationHelper getInstance() {

        if (helper == null) {

            helper = new LocationHelper();

        }

        return helper;

    }



    public void start() {

        if (locationClient == null) {


            //第一步实例化定位核心类

            locationClient = new LocationClient(MyApplication.getContext(), getLocOption());

            //第二步设置位置变化回调监听

            locationClient.registerLocationListener(locationListener);

        }
        //        第三步开始定位
        locationClient.start();

    }



//一般会在Activity的OnDestroy方法调用

    public void stop() {

        if (locationClient !=null) {

            locationClient.unRegisterLocationListener(locationListener);

            locationClient.stop();

            locationClient = null;

        }

    }



    private LocationClientOption getLocOption() {

        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setScanSpan(1000);

        return option;

    }



    private class MyBDLocationListener implements BDLocationListener

    {

        @Override

        public void onReceiveLocation(BDLocation bdLocation) {

            if (callBack != null&&bdLocation!=null){

                callBack.callBack(bdLocation.getAddrStr(),bdLocation.getStreetNumber(),bdLocation.getLatitude(),bdLocation.getLongitude(),bdLocation.getDistrict(),bdLocation.getStreet(),bdLocation.getCity(),bdLocation.getProvince());
            }

            //多次定位必须要调用stop方法

            locationClient.stop();

        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

    }



    public interface LocationCallBack {

        void callBack(String addr,String streetnumber ,double lat, double lng, String district ,String street,String city,String province);

    }



    public LocationCallBack getCallBack() {

        return callBack;

    }



    public void setCallBack(LocationCallBack callBack) {

        this.callBack = callBack;

    }

}